const express = require("express");
const router = express.Router();
const db = require("../../sqlServer/dbConnect");
const time = require("../../utils/time")
const email = require("../../utils/emailConfig");
const util = require("../../utils/index")
// 邮箱验证码
let emailCodeS
// 用户登录
router.post("/login", (req, res) => {
    const { userName, passWord } = req.body;
    const sql = "select Id,userName,name,role,status,email from user where userName=? and passWord=?"
    db.sqlQuery(sql, [userName, passWord], (err, result) => {
        if (err) {
            console.log(err)
        }
        if (result.length === 0) {
            res.send({
                msg: "用户不存在或密码不正确!",
                status: 203
            })
        } else {
            // console.log(result)
            if (result[0].status === "0") {
                res.send({
                    msg: "该用户已锁定!",
                    status: 203,
                })
            } else {
                res.send({
                    msg: "登陆成功",
                    status: 200,
                    data: result
                })
                db.sqlQuery("insert into log(doName,doInfo,doTime) values(?,?,?)", [userName, "用户登录", time.getData()])
            }
        }
    })
})

// 用户查询
router.post("/info", (req, res) => {
    const { values, pageConfig, doName } = req.body;
    const { page, pageSize } = pageConfig
    const sql = values === null ?
        'select Id,userName,name,role,status,email,createtime from user limit ?,?;select * from user' :
        "select Id,userName,name,role,status,email,createtime from user where name=? or status=? limit ?,?;select * from user where name=? or status=?"
    const data = values === null ? [(Number(page) - 1) * Number(pageSize), Number(pageSize)] :
        [values.name, values.status, (Number(page) - 1) * Number(pageSize), Number(pageSize), values.name, values.status]
    db.sqlQuery(sql, data, (err, result) => {
        if (err) {
            console.log(err)
        }
        if (result && result.length === 0) {
            res.send({
                msg: "用户不存在",
                status: 203
            })
        } else {
            res.send({
                msg: "获取成功",
                status: 200,
                data: result[0],
                total: result[1].length
            })
        }
    })
    db.sqlQuery("insert into log(doName,doInfo,doTime) values(?,?,?)", [doName, "用户查询", time.getData()])
})

// 用户添加
router.post("/add", (req, res) => {
    const { userName, passWord, role, name, email, doName } = req.body;
    const createtime = time.getData()
    const data = [userName, passWord, name, role, email, createtime]
    const sql = "insert into user(userName,passWord,name,role,email,createtime) values(?,?,?,?,?,?)"
    db.sqlQuery("select * from user where userName=?", data, (err, result) => {
        if (err) {
            console.log(err)
        } else {
            if (result.length >= 1) {
                res.send({
                    msg: "该账户已存在！",
                    status: 203
                })
            } else {
                db.sqlQuery(sql, data, (err) => {
                    if (err) {
                        console.log(err)
                    } else {
                        res.send({
                            msg: "添加成功",
                            status: 200
                        })
                    }
                })
            }
        }
    })
    db.sqlQuery("insert into log(doName,doInfo,doTime) values(?,?,?)", [doName, "用户添加", time.getData()])
})

// 用户编辑
router.post("/edit", (req, res) => {
    const { name, role, status, Id, doName } = req.body;
    const data = [name, role, status, Id]
    const sql = "update user set name=?,role=?,status=? where Id=?"
    db.sqlQuery(sql, data, (err) => {
        if (err) {
            console.log(err)
        } else {
            res.send({
                msg: "编辑成功！若是修改本账号，请重新登录！",
                status: 200
            })
        }
    })
    db.sqlQuery("insert into log(doName,doInfo,doTime) values(?,?,?)", [doName, "用户编辑", time.getData()])
})

// 用户-- 删除
router.post("/delete", (req, res) => {
    const { Id, doName } = req.body
    let sql = "delete from user where Id=?"
    const data = [Id]
    if (Id === 1) {
        res.send({
            status: 203,
            msg: "无权删除管理员账号！"
        })
        return
    } else {
        db.sqlQuery(sql, data, (err) => {
            if (err) {
                console.log(err)
                res.send({
                    msg: "删除失败",
                    status: 203
                })
            } else {
                res.send({
                    msg: "删除成功",
                    status: 200
                })
                db.sqlQuery("insert into log(doName,doInfo,doTime) values(?,?,?)", [doName, "用户删除", time.getData()])
            }
        })
    }
})

// 用户菜单权限查询
router.post("/menuPerms", (req, res) => {
    const { role } = req.body
    let menuList = []
    let powerList = []
    let sql = "select power from role where name=? "
    let sql1 = "select * from menu where Id=?;select * from menu"
    db.sqlQuery(sql, [role], (err, result) => {
        if (err) {
            console.log(err)
            res.send({ status: 203, msg: "获取菜单列表错误，请联系管理员！" })
        } else {
            powerList = result[0].power.split(",")
            powerList.map((id, index) => {
                db.sqlQuery(sql1, [Number(id)], (err, menu) => {
                    menuList.push(menu[0][0])
                    if (index >= powerList.length - 1) {
                        res.send(util.menuToTree(menuList,menu[1]))
                    }
                })
            })
        }
    })
})

// 用户按钮权限查询
router.post("/btnPower", (req, res) => {
    const { role } = req.body
    let btnList = []
    let powerList = []
    let sql = "select * from role where name=?"
    let sql1 = "select * from power where Id=?"
    db.sqlQuery(sql, [role], (err, result) => {
        if (err) {
            console.log(err)
        } else {
            powerList = result[0].btnPower.split(",")
            powerList.map((id, index) => {
                db.sqlQuery(sql1, [Number(id)], (err, btn) => {
                    btnList.push(btn[0].auth)
                    if (index >= powerList.length - 1) {
                        res.send({
                            data: btnList,
                            msg: "获取用户按钮权限成功",
                            status: 200
                        })
                    }
                })
            })
        }
    })
})

// 获取邮箱验证码
router.post("/userEmailCode", (req, res) => {
    const { userName } = req.body;
    const code = parseInt(Math.random() * 10000)
    emailCodeS = code
    const sql = "select name,email from user where userName=?"
    db.sqlQuery(sql, [userName], (err, result) => {
        if (err) {
            console.log(err)
        }
        if (result.length === 0) {
            res.send({
                msg: "用户不存在",
                status: 203
            })
        } else {
            //2、配置内容
            const msg = {
                from: '1563537197@qq.com', // 发送者邮箱
                to: `${result[0].email}`, // 目标邮箱号
                subject: `Hello ✔ ${result[0].name}`,
                text: `食品溯源管理系统提醒您！您修改当前账户的密码，确认是本人操作！验证码为${code},` // 发送的内容
            };
            //3.发送邮件
            email.sendMail(msg, function (err) {
                if (err) {
                    res.send({
                        msg: "系统邮箱授权码过期，请联系管理员！",
                        status: 203,
                    })
                } else {
                    res.send({
                        msg: "验证码获取成功，请查看邮箱",
                        status: 200,
                    })
                }
                email.close(); //发送完毕后关闭
            })
        }
    })

})

// 用户修改密码
router.post("/editPassword", (req, res) => {
    const { userName, emailCode, passWord } = req.body;
    const data = [passWord, userName]
    if (emailCode == emailCodeS) {
        const sql = "update user set passWord=? where userName=?"
        db.sqlQuery(sql, data, (err) => {
            if (err) {
                console.log(err)
            } else {
                res.send({
                    msg: "密码修改成功",
                    status: 200
                })
            }
        })
    } else {
        res.send({
            msg: "验证码错误",
            status: 200
        })
    }
    emailCodeS = null
    db.sqlQuery("insert into log(doName,doInfo,doTime) values(?,?,?)", [userName, "更改密码", time.getData()])
})


// 修改用户状态
router.post("/editUserSta", (req, res) => {
    const { status, Id, doName } = req.body;
    const sql = "update user set status=? where Id=?"
    db.sqlQuery(sql, [status, Id], (err, result) => {
        if (err) {
            console.log(err)
            res.send({
                status: 203,
                msg: "操作失败"
            })
        } else {
            if (status === "0") {
                res.send({
                    status: 200,
                    msg: "锁定成功"
                })
            } else {
                res.send({
                    status: 200,
                    msg: "解锁成功"
                })
            }
            db.sqlQuery("insert into log(doName,doInfo,doTime) values(?,?,?)", [doName, "更改用户状态", time.getData()])
        }
    })
})

module.exports = router